﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using Resources;
using ud_MenuHTML.Business;
using mojoPortal.Web.Framework;
using ud_Utilities;
using System.Collections;
using mojoPortal.Business;

namespace ud_MenuHTML
{
    public partial class MenuEdit : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private Guid itemGuid = Guid.Empty;
        MenuHTMLConfiguration config = new MenuHTMLConfiguration();
        protected string EditContentImage = WebConfigSettings.EditContentImage;
        protected string DeleteLinkImage = WebConfigSettings.DeleteLinkImage;
        protected string DeleteLinkText = MenuHTMLResource.ButtonDelete;
        protected string DeleteLinkImageUrl = string.Empty;
        protected string EditLinkText = MenuHTMLResource.ButtonEdit;
        protected string EditLinkImageUrl = string.Empty;
        readonly DBMenuHTML repository = new DBMenuHTML();
        tbl_MenuHTML item = new tbl_MenuHTML();

        void Page_Load(object sender, EventArgs e)
        {
            Page.EnableViewState = true;
            LoadSettings();
            if (!UserCanEditPage() || !UserCanViewPage() || !UserCanEditModule(moduleId))
            {
                WebUtils.SetupRedirect(this, SiteRoot + "/AccessDenied.aspx");
            }
            PopulateLabels();
            if (!Page.IsPostBack)
            {
                PopulateControls();
            }
        }

        private void PopulateControls()
        {
            BindTarget();
            BindData();
            BindEdit();
        }

        private void BindTarget()
        {
            if (Page.IsPostBack) return;
            ListItemCollection lic = new ListItemCollection
                                         {
                                             new ListItem("Self", "_self"),
                                             new ListItem("New", "_blank")
                                         };
            ddlTarget.DataSource = lic;
            ddlTarget.DataTextField = "Text";
            ddlTarget.DataValueField = "Value";
            ddlTarget.DataBind();
        }

        private void BindEdit()
        {
            if (Page.IsPostBack) return;
            if (itemGuid.Equals(Guid.Empty)) return;
            if (item == null) return;
            txtName.Text = item.Name;
            txtLink.Text = item.Link;
            txtOrder.Text = item.SortOrder.ToString();
            ddlTarget.Items.FindByValue(item.Target).Selected = true;
            if (!string.IsNullOrEmpty(item.ImageUrl))
            {
                divImage.Visible = true;
                imgView.ImageUrl = "~/" + ConfigurationManager.AppSettings["ArticleImagesFolder"] + item.ImageUrl;
            }
            else { divImage.Visible = false; }
        }

        private void BindData()
        {
            List<tbl_MenuHTML> items = repository.GetAll(moduleId);
            gvItems.DataSource = items;
            gvItems.DataBind();
            gvItems.AllowPaging = items.Count > 10;
        }

        private void LoadSettings()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
            itemGuid = WebUtils.ParseGuidFromQueryString("itemid", itemGuid);
            mp1.CssClass += config.CustomCssClass;
            item = repository.GetOne(itemGuid);
        }

        private void PopulateLabels()
        {
            PageTitle = SiteUtils.FormatPageTitle(siteSettings, MenuHTMLResource.MenuEditPage);
            ltrTitle.Text = MenuHTMLResource.MenuEditPage;
            btnBack.Text = MenuHTMLResource.ButtonBack;
            btnDelete.Text = MenuHTMLResource.ButtonDelete;
            btnSave.Text = MenuHTMLResource.ButtonSave;
            txtOrder.Text = @"0";
            gvItems.Columns[0].HeaderText = MenuHTMLResource.MenuName;
            gvItems.Columns[1].HeaderText = MenuHTMLResource.MenuOrder;
            EditLinkImageUrl = ImageSiteRoot + "/Data/SiteImages/" + EditContentImage;
            DeleteLinkImageUrl = ImageSiteRoot + "/Data/SiteImages/" + DeleteLinkImage;
            if (itemGuid.Equals(Guid.Empty))
            {
                btnDelete.Visible = false;
            }
            Utilities.AddConfirmButton(btnDelete, MenuHTMLResource.DeleteConfirmWarning);
        }

        void btnDelete_Click(object sender, EventArgs e)
        {
            repository.Delete(itemGuid);
            Refresh();
        }

        void btnBack_Click(object sender, EventArgs e)
        {
            WebUtils.SetupRedirect(this, SiteRoot + "/MenuHTML/Admin/MenuEdit.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString());
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void Save()
        {   
            string fileName;
            if (!SaveImageUrl(out fileName))
            {
                return;
            }
            if (!fileName.Equals(string.Empty))
            {
                item.ImageUrl = fileName;
            }
            if (itemGuid.Equals(Guid.Empty))
            {
                repository.Create(moduleId, txtName.Text, txtLink.Text, ddlTarget.SelectedValue, int.Parse(txtOrder.Text), Guid.Empty, fileName);
            }
            else
            {
                repository.Update(itemGuid, txtName.Text, txtLink.Text, ddlTarget.SelectedValue, int.Parse(txtOrder.Text), Guid.Empty, fileName);
                itemGuid = Guid.Empty;
            }
            Refresh();
        }

        private void Refresh()
        {
            WebUtils.SetupRedirect(this, SiteRoot + "/MenuHTML/Admin/MenuEdit.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString());
        }

        void gvItems_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("EditItem"))
            {
                itemGuid = new Guid(e.CommandArgument.ToString());
                WebUtils.SetupRedirect(this, SiteRoot + "/MenuHTML/Admin/MenuEdit.aspx?pageid="
                    + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&itemid=" + itemGuid);
            }
            else if (e.CommandName.Equals("DeleteItem"))
            {
                itemGuid = new Guid(e.CommandArgument.ToString());
                repository.Delete(itemGuid);
                WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
            }
        }

        void gvItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvItems.PageIndex = e.NewPageIndex;
            BindData();
        }

        void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType != DataControlRowType.DataRow) return;
            ImageButton ibtnDelete = e.Row.FindControl("ibtnDelete") as ImageButton;
            Utilities.AddConfirmButton(ibtnDelete, MenuHTMLResource.DeleteConfirmWarning);
        }

        private bool SaveImageUrl(out string fileName)
        {
            bool flag = false;
            int width = 0;
            int height = 0;
            fileName = string.Empty;
            try
            {
                //Check valid file upload
                if (fuImageUrl.FileName.Length > 0)
                {

                    string fileExtension = System.IO.Path.GetExtension(fuImageUrl.PostedFile.FileName);
// ReSharper disable PossibleLossOfFraction
                    Double fileSize = fuImageUrl.PostedFile.ContentLength / 1024;
// ReSharper restore PossibleLossOfFraction

                    //Kiem tra ten mo rong file upload
                    if (!Utilities.IsValidFileExtension(fileExtension, "AllowedImageFileExtensions"))
                    {
                        lblImageUrlError.Text = MenuHTMLResource.ImageUrlErrorFileExtension;
                        return false;
                    }
                    //Kiem tra kich thuoc file upload
                    if (!Utilities.IsValidFileSize(fileSize, "AllowedImageSize"))
                    {
                        lblImageUrlError.Text = MenuHTMLResource.ImageUrlErrorFileSize + ConfigurationManager.AppSettings["AllowedImageSize"] + @" KB";
                        return false;
                    }
                    string path = Server.MapPath("~/" + ConfigurationManager.AppSettings["ArticleImagesFolder"]);
                    string guid = Guid.NewGuid().ToString().Replace("-", "").ToUpper();
                    using (System.Drawing.Image image = System.Drawing.Image.FromStream(fuImageUrl.PostedFile.InputStream))
                    {
                        int resizeWidth;
                        int.TryParse(ConfigurationManager.AppSettings["ArticleImageMaxWidth"], out resizeWidth);
                        int resizeHeight;
                        int.TryParse(ConfigurationManager.AppSettings["ArticleImageMaxHeight"], out resizeHeight);
                        int thumbnailWidth;
                        int.TryParse(ConfigurationManager.AppSettings["ArticleImageMaxThumbnailWidth"], out thumbnailWidth);
                        int thumbnailHeight;
                        int.TryParse(ConfigurationManager.AppSettings["ArticleImageMaxThumbnailHeight"], out thumbnailHeight);
                        Utilities.ResizeImage(ref width, ref height, resizeWidth, resizeHeight, image.Width, image.Height);
                        fileName = path + guid + "_t" + fileExtension;
                        if (height != 0)
                        {
                            using (Bitmap bitmap = new Bitmap(image, width, height))
                            {
                                bitmap.Save(fileName, image.RawFormat);
                            }
                        }
                        else
                        {
                            fuImageUrl.PostedFile.SaveAs(fileName);
                        }
                        Utilities.ResizeImage(ref width, ref height, thumbnailWidth, thumbnailHeight, image.Width, image.Height);
                        fileName = path + guid + fileExtension;
                        if (height != 0)
                        {
                            using (Bitmap bitmap = new Bitmap(image, width, height))
                            {
                                bitmap.Save(fileName, image.RawFormat);
                            }
                        }
                        else
                        {
                            fuImageUrl.PostedFile.SaveAs(fileName);
                        }
                    }
                    fileName = guid + fileExtension;
                    if (!item.ImageUrl.Equals(string.Empty))
                    {
                        DeleteImageFromServer();
                    }
                    flag = true;
                }
                else
                {
                    flag = true;
                }
            }
            catch (Exception e)
            {
                lblImageUrlError.Visible = true;
                lblImageUrlError.Text = e.Message;//"Error when upload image";
            }
            return flag;
        }
        private void DeleteImageFromServer()
        {
            string thumbnailImageURL = Request.PhysicalApplicationPath + ConfigurationManager.AppSettings["ArticleImagesFolder"] + item.ImageUrl;
            thumbnailImageURL = thumbnailImageURL.Replace("/", "\\");
            string imageURL = thumbnailImageURL.Substring(0, thumbnailImageURL.LastIndexOf(".")) + "_t" + thumbnailImageURL.Substring(thumbnailImageURL.LastIndexOf("."));
            if (System.IO.File.Exists(imageURL))
            {
                System.IO.File.Delete(imageURL);
            }
            if (System.IO.File.Exists(thumbnailImageURL))
            {
                System.IO.File.Delete(thumbnailImageURL);
            }
        }
        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
            Load += Page_Load;
        }

        protected override void OnInit(EventArgs e)
        {
            LoadPanels();
            base.OnInit(e);
            SuppressPageMenu();
            btnSave.Click += btnSave_Click;
            btnBack.Click += btnBack_Click;
            btnDelete.Click += btnDelete_Click;
            gvItems.RowCommand += gvItems_RowCommand;
            gvItems.RowDataBound += gvItems_RowDataBound;
            gvItems.PageIndexChanging += gvItems_PageIndexChanging;
            btnDeleteImg.Click += btnDeleteImg_Click;
        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            config = new MenuHTMLConfiguration(settings);
            bool showLeftColumnAdmin = ConfigHelper.GetBoolProperty("ShowLeftColumnAdmin", false);
            bool showRightColumnAdmin = ConfigHelper.GetBoolProperty("ShowRightColumnAdmin", false);
            bool showTopColumnAdmin = ConfigHelper.GetBoolProperty("ShowTopColumnAdmin", false);
            bool showBottomColumnAdmin = ConfigHelper.GetBoolProperty("ShowBottomColumnAdmin", false);
            int showCenterColumnAdmin = ConfigHelper.GetIntProperty("ShowCenterColumnAdmin", 0);
            LoadSideContent(showLeftColumnAdmin, showRightColumnAdmin, showTopColumnAdmin, showBottomColumnAdmin, showCenterColumnAdmin);
        }

        void btnDeleteImg_Click(object sender, ImageClickEventArgs e)
        {
            if (item == null)
            {
                item = repository.GetOne(itemGuid);
            }
            DeleteImageFromServer();
            divImage.Visible = false;
            repository.Update(itemGuid, txtName.Text, txtLink.Text, ddlTarget.SelectedValue, int.Parse(txtOrder.Text), Guid.Empty, string.Empty);
        }
        #endregion
    }
}